package com.zhanghe.mall.service.impl;

import com.zhanghe.mall.pojo.AttributeProperty;
import com.zhanghe.mall.pojo.ClassificationAttribute;
import com.zhanghe.mall.pojo.CommodityClassification;
import com.zhanghe.mall.pojo.repository.AttributePropertyRepository;
import com.zhanghe.mall.pojo.repository.ClassificationAttributeRepository;
import com.zhanghe.mall.service.ClassificationAttributeService;
import com.zhanghe.mall.service.dto.AddClassificationAttributeDTO;
import com.zhanghe.mall.service.vo.AttributePropertyVO;
import com.zhanghe.mall.service.vo.ClassificationAttributeVO;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Throwable.class)
public class ClassificationAttributeServiceImpl implements ClassificationAttributeService {

  @Autowired
  private ClassificationAttributeRepository classificationAttributeRepository;

  @Autowired
  private AttributePropertyRepository attributePropertyRepository;

  @Override
  public List<ClassificationAttributeVO> findByClassificationId(Long classificationId) {
    return classificationAttributeRepository.findByCommodityClassification_Id(classificationId).stream().map(classificationAttribute -> {
      ClassificationAttributeVO classificationAttributeVO = ClassificationAttributeVO.transform(classificationAttribute);
      List<AttributeProperty> list = attributePropertyRepository.findByClassificationAttribute_IdOrderBySort(classificationAttribute.getId());
      classificationAttributeVO.setSystemAttributeProperty(AttributePropertyVO.transform(list));
      return classificationAttributeVO;
    }).collect(Collectors.toList());
  }

  @Override
  public ClassificationAttribute insert(
      AddClassificationAttributeDTO addClassificationAttributeDTO) {
    ClassificationAttribute classificationAttribute = new ClassificationAttribute();
    BeanUtils.copyProperties(addClassificationAttributeDTO,classificationAttribute);
    CommodityClassification commodityClassification = new CommodityClassification();
    commodityClassification.setId(addClassificationAttributeDTO.getCommodityClassificationId());
    classificationAttribute.setCommodityClassification(commodityClassification);
    return classificationAttributeRepository.save(classificationAttribute);
  }
}
